package cn.javazd.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DomXml implements Xml {

	@Override
	public void createXml() {
		long startTime = System.currentTimeMillis();
		try {
			//创建解析器
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = factory.newDocumentBuilder();
			Document document = db.newDocument();

			document.setXmlStandalone(true);
			Element app = document.createElement("app");
			Element phone = document.createElement("phone");
			phone.setAttribute("type", "IOS 11.1");
			
			Element version = document.createElement("version");
			version.setTextContent("1.0");
			Element name = document.createElement("name");
			name.setTextContent("iphone 8");
			Element color = document.createElement("color");
			color.setTextContent("磨砂黑");

			phone.appendChild(version);
			phone.appendChild(name);
			phone.appendChild(color);
			
			app.appendChild(phone);
			document.appendChild(app);

			TransformerFactory tff = TransformerFactory.newInstance();
			Transformer tf = tff.newTransformer();

			// 输出内容是否使用换行
			tf.setOutputProperty(OutputKeys.INDENT, "yes");
			tf.transform(new DOMSource(document), new StreamResult(new File("Dom-app.xml")));

			System.out.print("create Dom xml success ==== ");
			System.out.println("speed times: " + (System.currentTimeMillis() - startTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
